const Chat = require('../models/chat.js')
const { Op } = require("sequelize");

// 添加聊天记录
//
let lastExecutionTime = 0;
//
const addChat = async (chat) => {
  //
  const limitInterval = 1000;
  // 获取当前时间戳
  const currentTime = new Date().getTime();
  if (currentTime - lastExecutionTime < limitInterval) {
    console.log('P wait.');
    setTimeout(() => {
      // 在这里执行需要等待 1 秒后执行的操作
      console.log('100 秒后执行的操作');
    }, 1000);
    //return res.status(429).json({ message: 'Too frequent calls. Please wait.' });
  }



  // 更新上次执行时间
  lastExecutionTime = currentTime;
  //
  console.log('1');
  const res = await Chat.create(chat)
  console.log('2');
  return Boolean(res)
}

// 获取聊天列表
const getChatList = async (sessionId, lastTime) => {
  return await Chat.findAll({
    where: {
      sessionId,
      updatedAt: {
        [Op.lt]: lastTime
      }
    },
    limit: 30,
    order: [
      ['updatedAt', 'DESC'],
    ],
    attributes: ['senderId', 'receiverId', 'content', 'type', 'updatedAt', 'sort', 'others'],
    raw: true,
  })
}

module.exports = {
  addChat,
  getChatList,
}